package kt.com.bilin.coin.ui.fragment

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kt.com.bilin.coin.api.ApiObserver
import kt.com.bilin.coin.api.ApiRequest
import kt.com.bilin.coin.listener.OnStartActivityListener
import kt.com.bilin.coin.utils.Logger
import org.greenrobot.eventbus.EventBus

/**
 * Created by vicky on 2016/11/7.
 */
fun <T> Fragment.launchUI(
        block: suspend CoroutineScope.() -> T, apiObserver: ApiObserver<T>? = null, error: ((Throwable) -> Unit)? = null, complete: (() -> Unit)? = null,
): Job = ApiRequest(lifecycleScope).launchUI(block, error, complete, apiObserver)

open class BaseFragment(private val layoutResID: Int? = null) : Fragment(), OnStartActivityListener, View.OnClickListener {
    protected var mView: View? = null
    protected var mSavedInstanceState: Bundle? = null
    private val dispatcher by lazy { requireActivity().onBackPressedDispatcher }
    private val callback: OnBackPressedCallback = object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            onBackPressed()
        }
    }

    fun onBackPressed() {
        callback.isEnabled = false
        dispatcher.onBackPressed()
    }

    fun hasExtras(): Boolean {
        return arguments != null
    }

    override fun getView(): View? {
        return mView
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        try {
            mView = if (layoutResID != null) {
                inflater.inflate(layoutResID, null)
            } else {
                super.onCreateView(inflater, container, savedInstanceState)
            }
            mSavedInstanceState = savedInstanceState
            init(mView, savedInstanceState)
            initView(mView, savedInstanceState)
            initData(mView, savedInstanceState)
        } catch (e: Exception) {
            Logger.e(e)
        }
        return mView
    }

    open fun init(rootView: View?, savedInstanceState: Bundle?) {}
    open fun initView(rootView: View?, savedInstanceState: Bundle?) {}
    open fun initData(rootView: View?, savedInstanceState: Bundle?) {}

    override fun onClick(v: View?) {

    }

    override fun onStart() {
        super.onStart()
        if (!EventBus.getDefault().isRegistered(this)) {
            kotlin.runCatching { EventBus.getDefault().register(this) }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun goActicity(clazz: Class<*>, bundle: Bundle?, requestCode: Int?) {
        val intent = Intent(context, clazz)
        bundle?.let { intent.putExtras(it) }
        if (requestCode != null) {
            startActivityForResult(intent, requestCode)
        } else {
            startActivity(intent)
        }
    }

    override fun goActicityFinish(clazz: Class<*>, bundle: Bundle?, requestCode: Int?) {
        goActicity(clazz, bundle, requestCode)
        activity?.finish()
    }

}